package org.jeecg.common.fapiao.glority;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.jeecg.common.util.EmptyUtil;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class GlorityService {

    //这里输入提供的app_key
    private static final String appKey = "60e40d1f";

    //这里输入提供的app_secret
    private static final String appSecret = "d24f2ce135aacd8f07c442f8d3f61f21";

    // 单张发票识别
    private static final String itemInfoUrl = "https://fapiao.glority.cn/v1/item/get_item_info";

    // 多张发票识别
    private static final String multipleItemsInfoUrl = "https://fapiao.glority.cn/v1/item/get_multiple_items_info";

    // 发票识别并验真
    private static final String fapiaoValidationUrl = "https://fapiao.glority.cn/v1/item/fapiao_validation";

    // 多张发票识别
    private static final String itemInfoWithValidationUrl = "https://fapiao.glority.cn/v1/item/get_item_info_with_validation";

    /**
     * 以图片路径的形式上传
     * @param imageUrl
     * @return
     * @throws IOException
     */
    public static String getItemInfo(String imageUrl) throws IOException {

        long timestamp = System.currentTimeMillis() / 1000;
        String token = new Md5Hash(appKey + "+" + timestamp + "+" + appSecret).toString();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(itemInfoUrl)
                .post(new FormBody.Builder()
                        .add("app_key", appKey)
                        .add("timestamp", String.valueOf(timestamp))
                        .add("token", token)
                        .add("image_url", imageUrl)
                        .build())
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 发票上传 以Base64的格式上传 经测试暂时不可用
     * @param base64
     * @return
     * @throws IOException
     */
    public static String getItemInfoForBase64(String base64) throws IOException {

        long timestamp = System.currentTimeMillis() / 1000;
        String token = new Md5Hash(appKey + "+" + timestamp + "+" + appSecret).toString();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(itemInfoUrl)
                .post(new FormBody.Builder()
                        .add("app_key", appKey)
                        .add("timestamp", String.valueOf(timestamp))
                        .add("token", token)
                        .add("image_data", base64)
                        .build())
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 以图片路径的形式上传
     * @param file 要上传的文件
     * @return
     * @throws IOException
     */
    public static String getItemInfo(File file) throws IOException {

        long timestamp = System.currentTimeMillis() / 1000;
        String token = new Md5Hash(appKey + "+" + timestamp + "+" + appSecret).toString();

        // update-begin by wmf at 2022/3/30 19:00 for: 设置请求超时时间
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60L, TimeUnit.SECONDS)
                .writeTimeout(60L, TimeUnit.SECONDS)
                .readTimeout(60L, TimeUnit.SECONDS)
                .build();
        // update-end by wmf at 2022/3/30 19:00 for: 设置请求超时时间
        
        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("app_key", appKey)
                .addFormDataPart("timestamp", String.valueOf(timestamp))
                .addFormDataPart("token",token)
                .addFormDataPart("image_file", file.getName(),
                        RequestBody.create(file,MediaType.parse("application/octet-stream")))
                .build();
        Request request = new Request.Builder()
                .url(itemInfoUrl)
                .post(multipartBody)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 发票识别并且验真
     * @param file 要上传的文件
     * @return
     * @throws IOException
     */
    public static String getItemInfoWithValidation(File file) throws IOException {
        long timestamp = System.currentTimeMillis() / 1000;
        String token = new Md5Hash(appKey + "+" + timestamp + "+" + appSecret).toString();

        // update-begin-by wujinbiao 2022/3/31 8:54 for 设置请求超时时间
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60L, TimeUnit.SECONDS)
                .writeTimeout(60L, TimeUnit.SECONDS)
                .readTimeout(60L, TimeUnit.SECONDS)
                .build();
        // update-end-by wujinbiao 2022/3/31 8:54 for 设置请求超时时间

        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("app_key", appKey)
                .addFormDataPart("timestamp", String.valueOf(timestamp))
                .addFormDataPart("token",token)
                .addFormDataPart("image_file", file.getName(),
                        RequestBody.create(file,MediaType.parse("application/octet-stream")))
                .build();
        Request request = new Request.Builder()
                .url(itemInfoWithValidationUrl)
                .post(multipartBody)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 发票验真
     * @param map
     * @return
     * @throws IOException
     */
    public static String getFapiaoValidation(Map map) throws IOException {
        long timestamp = System.currentTimeMillis() / 1000;
        String token = new Md5Hash(appKey + "+" + timestamp + "+" + appSecret).toString();

        // update-begin-by wujinbiao 2022/3/31 8:54 for 设置请求超时时间
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60L, TimeUnit.SECONDS)
                .writeTimeout(60L, TimeUnit.SECONDS)
                .readTimeout(60L, TimeUnit.SECONDS)
                .build();
        // update-end-by wujinbiao 2022/3/31 8:54 for 设置请求超时时间

        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("app_key", appKey)
                .addFormDataPart("timestamp", String.valueOf(timestamp))
                .addFormDataPart("token",token)
                .addFormDataPart("code", EmptyUtil.checkNull(map.get("code")))
                .addFormDataPart("number", EmptyUtil.checkNull(map.get("number")))
                .addFormDataPart("date", EmptyUtil.checkNull(map.get("date")))
                .addFormDataPart("type", EmptyUtil.checkNull(map.get("type")))
                .addFormDataPart("check_code", EmptyUtil.checkNull(map.get("check_code")))
                .addFormDataPart("electronic_mark", EmptyUtil.checkNull(map.get("electronic_mark")))
                .addFormDataPart("pretax_amount", EmptyUtil.checkNull(map.get("pretax_amount")))
                .build();
        Request request = new Request.Builder()
                .url(fapiaoValidationUrl)
                .post(multipartBody)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public static void main(String[] args) throws IOException {
//        File file = new File("C:\\Users\\Administrator\\Pictures\\fapiao\\20210513104727.jpg");
//        File file = new File("D:\\pic\\jdfp.jpg");//机打发票 客运汽车
//        File file = new File("D:\\pic\\zzspp.jpg");//增值税专用发票 zzspp2.pdf
//        File file = new File("D:\\pic\\defp.jpg"); // 定额发票
//        File file = new File("D:\\pic\\zzspp2.pdf");// 增值税电子普通发票
//        File file = new File("D:\\pic\\可报销其他发票.jpg");// 可报销其他发票
//        File file = new File("D:\\pic\\hcp.jpg");// 可报销其他发票
//        File file = new File("D:\\pic\\jdfp2.jpg");//机打发票 出租車
//        File file = new File("D:\\pic\\二手车统一销售发票.jpg");//二手车统一销售发票
//        File file = new File("D:\\pic\\glf.jpg");//二手车统一销售发票
//        File file = new File("D:\\pic\\航空运输电子客票行程单.jpg");//航空运输电子客票行程单
//        File file = new File("D:\\pic\\船票4.jpg");//船票
//        File file = new File("D:\\pic\\机动车销售统一发票.jpg");//机动车销售统一发票
//        File file = new File("D:\\pic\\增值税普通发票卷票.jpeg");//增值税普通发票卷票
//        File file = new File("D:\\pic\\zzszyfp.jpg");//增值税专用发票
        File file = new File("C:\\Users\\Administrator\\Desktop\\发票2.jpg");//曹操出行电子行程单.pdf
        String result = GlorityService.getItemInfo(file);
        System.out.println(result);
        System.out.println("-------------------------------------");

        JSONObject jsonObject = JSON.parseObject(result);
        JSONObject rsdata = jsonObject.parseObject(jsonObject.getString("response")).getJSONObject("data");
        JSONArray identifyResults = rsdata.getJSONArray("identify_results");
        for (int idx = 0; idx < identifyResults.size(); idx++) {
            JSONObject rs = identifyResults.getJSONObject(idx);
            JSONObject data = rs.getJSONObject("details");
            String type = rs.getString("type");
            String code = data.getString("code");
            String number = data.getString("number");
            String date = data.getString("date");
            String check_code = data.getString("check_code");
            if(check_code != null && check_code.length() > 6){
                check_code = check_code.substring(check_code.length() - 6,check_code.length());
            }
            String electronic_mark = data.getString("electronic_mark") != null ? data.getString("electronic_mark") : "0";
            String pretax_amount = data.getString("pretax_amount");

            Map map = new HashMap();
            map.put("code",code);
            map.put("number",number);
            map.put("date",date);
            map.put("type",type);
            map.put("check_code",check_code);
            map.put("electronic_mark",electronic_mark);
            map.put("pretax_amount",pretax_amount);
            String result2 = GlorityService.getFapiaoValidation(map);
            System.out.println(result2);
        }

//        String base64 = ImageBase64Converter.convertFileToBase64(file.getPath());
//        String result = GlorityService.getItemInfoForBase64(base64);
//        String imgurl = "http://27.148.196.37:9092/qixin-boot/sys/common/getFile/20210513111851_1625671510592.jpg";
//        String result = GlorityService.getItemInfo(imgurl);

        String res = "{\"result\":1,\"response\":{\"data\":{\"version\":\"20210701\",\"result\":1,\"timestamp\":1625673835,\"message\":\"success\",\"id\":\"1ebf1238883580ac7aca825321326b22\",\"sha1\":\"be7e76ce84a07959fd3996b63ab073d877750b99\",\"time_cost\":\"561\",\"identify_results\":[{\"type\":\"10101\",\"orientation\":0,\"details\":{\"code\":\"035002000104\",\"number\":\"04114375\",\"date\":\"2021\\u5e7405\\u670806\\u65e5\",\"pretax_amount\":\"99.01\",\"tax\":\"0.99\",\"check_code\":\"04752747319193962050\",\"total\":\"100.00\",\"seller\":\"\\u798f\\u5dde\\u5e02\\u4ed3\\u5c71\\u533a\\u60a6\\u5ba2\\u697c\\u9910\\u996e\\u5e97\",\"seller_tax_id\":\"92350104MA34M1MK23\",\"buyer\":\"\\u798f\\u5efa\\u6d77\\u5ce1\\u519b\\u6c11\\u878d\\u5408\\u4ea7\\u4e1a\\u53d1\\u5c55\\u6709\\u9650\\u516c\\u53f8\",\"buyer_tax_id\":\"91350104MA33LG6952\",\"company_seal\":\"1\",\"form_type\":\"\\u7b2c\\u4e8c\\u8054\",\"form_name\":\"\\u53d1\\u7968\\u8054\",\"kind\":\"\\u9910\\u996e\",\"ciphertext\":\"00778-6>94+*>-23<4<4657*+1+4,07<1**60-3\\/*9+8<31+4+3*8349<,>21\\/664<<37+5\\/>378<18<\\/-9441,*5+7*52\\/8>>1<801197*06040<3\\/\",\"machine_code\":\"917002890355\",\"receiptor\":\"\",\"reviewer\":\"\",\"issuer\":\"\\u738b\\u4e3d\\u6587\",\"province\":\"\\u798f\\u5efa\\u7701\",\"city\":\"\",\"service_name\":\"\\u9910\\u996e\\u670d\\u52a1\",\"remark\":\"\",\"item_names\":\"*\\u9910\\u996e\\u670d\\u52a1*\\u9910\\u8d39\",\"items\":[{\"name\":\"*\\u9910\\u996e\\u670d\\u52a1*\\u9910\\u8d39\",\"total\":\"99.01\",\"tax_rate\":\"1%\",\"tax\":\"0\"}],\"code_confirm\":\"035002000\",\"number_confirm\":\"041143\",\"total_cn\":\"\\u58f9\\u4f70\\u5706\\u6574\"},\"extra\":{\"check_code_candidates\":[\"04752747319193962050\",\"04752747319193962056\"],\"check_code_last_six\":[\"962050\",\"962056\"],\"number_order_error\":[\"041143\"],\"qrcode\":[\"01,04,035002000104,04114375,99.01,20210506,04752747319193962050,4F1F,\"]}}]}}}";
/*
        JSONObject jsonObject = JSON.parseObject(res);
        if (jsonObject.getIntValue("result") == 0){
            System.out.println(res);
        }
        // 获取返回值，对返回值进行解析
        JSONObject rsdata = jsonObject.parseObject(jsonObject.getString("response")).getJSONObject("data");
        JSONArray identifyResults = rsdata.getJSONArray("identify_results");
        for (int idx = 0; idx < identifyResults.size(); idx++){
            JSONObject data = identifyResults.getJSONObject(idx);
            if ("10101".equals(data.getString("type"))){
                // 增值税票

            }
        }*/
        String ss = "20210513104727.jpg";
        String[] strs = ss.split("\\.");
//        System.out.println(strs[1]);

    }

/*    public static void main(String...args) throws IOException {

//        String appKey = "APPKEY"; //这里输入提供的app_key
//        String appSecret = "APPSECRET"; //这里输入提供的app_secret

        String imageUrl = "http://27.148.196.37:9092/qixin-boot/sys/common/getFile/20210513111851_1625671510592.jpg";
        String host = "http://fapiao.glority.cn/v1/item/get_item_info";
        long timestamp = System.currentTimeMillis() / 1000;
        String token = new Md5Hash(appKey + "+" + timestamp + "+" + appSecret).toString();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(host)
                .post(new FormBody.Builder()
                        .add("app_key", appKey)
                        .add("timestamp", String.valueOf(timestamp))
                        .add("token", token)
                        .add("image_url", imageUrl)
                        .build())
                .build();

        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }*/

}
